<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="个人设置"></pageHeaderNew>
    </template>
    <main class="wrap">
      <div class="title-box">
        <div class="title">
          <div
            :style="{
              marginLeft: '25px'
            }"
          >
            基本信息
          </div>
          <div></div>
        </div>
      </div>
      <div
        style="
          width: 100%;
          margin: 20px auto;
          display: flex;
          justify-content: center;
        "
      >
        <div
          class="infoDataAAA"
          style="
            margin: 20px auto;
            width: 100%;
            display: flex;
            justify-content: center;
          "
        >
          <a-space
            direction="vertical"
            class="infoDataAAA-main"
            :style="{
              marginRight: '80px'
            }"
            style="
              padding: 12px 12px 0px 12px;
              width: 30%;
              margin-bottom: 20px;
              border: 1px solid #d5d5d5;
              border-radius: 5px;
            "
          >
            <a-row class="grid-demo">
              <a-col flex="auto">
                <div>系统头像</div>
              </a-col>
              <a-col flex="80px">
                <a-avatar
                  :size="50"
                  v-model:imageUrl="userData.headPortrait"
                  :style="{ backgroundColor: '#3c6eff' }"
                >
                  <IconUser />
                  <!-- <template #trigger-icon>
                    <IconEdit />
                  </template> -->
                </a-avatar>
              </a-col>
            </a-row>
            <a-row class="grid-demo">
              <a-col flex="auto">
                <div style="color: #868686">更换系统头像</div>
              </a-col>
              <a-col flex="80px">
                <a-button @click="toast(1)">修改</a-button>
              </a-col>
            </a-row>
          </a-space>
          <a-space
            direction="vertical"
            class="infoDataAAA-main"
            style="
              padding: 12px 12px 0px 12px;
              width: 30%;
              margin-bottom: 20px;
              border: 1px solid #d5d5d5;
              border-radius: 5px;
            "
          >
            <a-row class="grid-demo">
              <a-col flex="auto">
                <div>个人主页头像</div>
              </a-col>
              <a-col flex="80px">
                <a-avatar
                  :size="50"
                  v-model:imageUrl="userData.personalHeadPortrait"
                  :style="{ backgroundColor: '#3c6eff' }"
                >
                  <IconUser />
                  <!-- <template #trigger-icon>
                    <IconEdit />
                  </template> -->
                </a-avatar>
              </a-col>
            </a-row>
            <a-row class="grid-demo">
              <a-col flex="auto">
                <div style="color: #868686">更换个人主页头像</div>
              </a-col>
              <a-col flex="80px">
                <a-button @click="toast(2)">修改</a-button>
              </a-col>
            </a-row>
          </a-space>
        </div>
        <!-- <a-space style="margin-right: 80px" direction="vertical" align="center">
          <a-avatar
            :size="100"
            @click="toast(2)"
            :imageUrl="userData.headPortrait"
            :style="{ backgroundColor: '#3c6eff' }"
          >
            <IconUser />
            <template #trigger-icon>
              <IconEdit />
            </template>
          </a-avatar>
          <p style="margin-top: 10px">系统头像</p>
        </a-space>
        <a-space direction="vertical" align="center">
          <a-avatar
            :size="100"
            :imageUrl="userData.personalHeadPortrait"
            @click="toast(2)"
            :style="{ backgroundColor: '#3c6eff' }"
          >
            <IconUser />
            <template #trigger-icon>
              <IconEdit />
            </template>
          </a-avatar>
          <p style="margin: 0; margin-top: 10px">个人主页头像</p>
        </a-space> -->
      </div>
      <!-- <a-form
        auto-label-width
        :model="{}"
        :style="{ width: '200px', margin: '0 auto' }"
      >
        <a-form-item field="name" label="系统头像" show-colon> </a-form-item>
        <a-form-item label="个人主页头像" show-colon> </a-form-item> -->
      <!-- <a-form-item label="姓名" show-colon>
          {{ userData.name || '---' }}
        </a-form-item>
        <a-form-item label="工号" show-colon>
          {{ userData.jobNumber || '---' }}
        </a-form-item>
        <a-form-item label="工作手机" show-colon>
          {{ userData.mobile || '---' }}
        </a-form-item> -->
      <!-- </a-form> -->
      <div class="title-box">
        <div class="title">
          <div
            :style="{
              marginLeft: '25px'
            }"
          >
            账号信息
          </div>
          <div></div>
        </div>
      </div>

      <div
        class="infoDataAAA"
        style="
          margin: 20px auto;
          width: 100%;
          display: flex;
          justify-content: center;
        "
      >
        <a-space
          v-for="(info, index) in infoData"
          :key="info.key"
          direction="vertical"
          class="infoDataAAA-main"
          :style="{
            marginRight: !index ? '80px' : null
          }"
          style="
            padding: 12px 12px 0px 12px;
            width: 30%;
            margin-bottom: 20px;
            border: 1px solid #d5d5d5;
            border-radius: 5px;
          "
        >
          <a-row class="grid-demo">
            <a-col flex="auto">
              <div>{{ info.name }}</div>
            </a-col>
            <a-col flex="100px">
              <div style="color: #868686">{{ info.data }}</div>
            </a-col>
          </a-row>
          <a-row class="grid-demo">
            <a-col flex="auto">
              <div style="color: #868686">{{ info.info }}</div>
            </a-col>
            <a-col flex="100px">
              <a-button
                @click="open(info.key, info.type)"
                :type="info.type === 1 ? 'primary' : 'outline'"
                >{{ info.type === 1 ? '修改' : '绑定' }}</a-button
              >
            </a-col>
          </a-row>
        </a-space>
      </div>
    </main>
  </ContentCard>
  <footer>
    <a-button
      class="btn"
      style="
        margin-right: 20px;
        border: 1px rgba(242, 242, 242, 1) solid;
        background-color: #fff;
      "
      @click="$router.go(-1)"
    >
      返回
    </a-button>
    <a-button class="btn" type="primary" @click="save">保存</a-button>
  </footer>
  <a-modal
    :width="800"
    @ok="handleOk"
    @cancel="visible = false"
    :visible="visible"
    title="图片裁剪上传"
  >
    <a-space>
      本地上传
      <a-upload :custom-request="customRequest">
        <template #upload-item> </template>
      </a-upload>
    </a-space>
    <div class="cut">
      <vue-cropper
        ref="cropper"
        :img="imgUrl"
        :output-size="1"
        output-type="png"
        :info="true"
        :full="false"
        :fixed="false"
        :fixed-number="[75.34]"
        :can-move="true"
        :can-move-box="true"
        :fixed-box="false"
        :original="false"
        :auto-crop="true"
        :auto-crop-width="750"
        :auto-crop-height="340"
        :center-box="true"
        :high="true"
        mode="contain"
        :max-img-size="99999"
      ></vue-cropper>
    </div>
  </a-modal>
  <a-modal
    :width="800"
    @ok="handleOkMobile"
    @cancel="visibleMobile = false"
    :visible="visibleMobile"
    title="修改手机号码"
  >
    <a-form
      auto-label-width
      :model="{}"
      :style="{ width: '70%', margin: '0 auto' }"
    >
      <a-form-item label="原手机号码" show-colon required>
        <div
          style="
            width: 100%;
            height: 32px;
            line-height: 32px;
            background: #f2f3f5;
            color: #6d7076;
            padding-left: 5px;
            border-radius: 5px;
            cursor: not-allowed;
          "
        >
          {{ userData.mobile }}
        </div>
      </a-form-item>
      <a-form-item
        label="新手机号码"
        show-colon
        required
        :help="help"
        :validate-status="validateStatus"
      >
        <a-input v-model="newMobile"></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal
    :width="800"
    @ok="handleOkPassword"
    @cancel="visiblePassword = false"
    :visible="visiblePassword"
    title="修改密码"
  >
    <a-form
      auto-label-width
      :model="{}"
      :style="{ width: '70%', margin: '0 auto' }"
    >
      <a-form-item label="旧密码" show-colon required>
        <div
          style="
            width: 100%;
            height: 32px;
            line-height: 32px;
            background: #f2f3f5;
            color: #6d7076;
            padding-left: 5px;
            border-radius: 5px;
            cursor: not-allowed;
          "
        >
          *******
        </div>
      </a-form-item>
      <a-form-item
        label="新密码"
        show-colon
        required
        :help="help"
        :validate-status="validateStatus"
      >
        <a-input-password
          v-model:visibility="visibility"
          v-model="Password"
          placeholder="请输入新密码"
          :defaultVisibility="false"
          allow-clear
        />
      </a-form-item>
      <a-form-item
        label="确认密码"
        show-colon
        required
        :help="help"
        :validate-status="validateStatus"
      >
        <a-input-password
          v-model="newPassword"
          v-model:visibility="newVisibility"
          placeholder="请再次输入新密码"
          :defaultVisibility="false"
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { useUserStore } from '@/store';
import { avatarSetting } from '@/utils/file';
import 'vue-cropper/dist/index.css';
import { Message, RequestOption } from '@arco-design/web-vue';
import { VueCropper } from 'vue-cropper';
import { personalInfo, putPersonalInfo } from '@/apis/base/user/index';
import router from '@/router';
type TVueCropper = InstanceType<typeof VueCropper>;
const phoneNumberPattern = /^1[345789]\d{9}$/;
const userStore = useUserStore();

const userData: any = reactive({});
const newMobile = ref();
const Password = ref();
const newPassword = ref();

const visibleMobile = ref(false);
const visiblePassword = ref(false);

const visibility = ref(true);
const newVisibility = ref(true);

const infoData = reactive([
  {
    key: 'mobile',
    name: '手机号',
    info: '手机号变更后，登录账号将发生改变，请谨慎操作',
    data: '',
    type: 2
  },
  // {
  //   key: 'email',
  //   name: '邮箱',
  //   info: '接收人事提醒，消息查看更及时。',
  //   data: '',
  //   type: 2
  // },
  // {
  //   key: 'WeChat',
  //   name: '微信',
  //   info: '接收人事提醒，消息查看更及时。',
  //   data: '',
  //   type: 2
  // },
  {
    key: 'password',
    name: '登录密码',
    info: '修改密码将退出系统',
    data: '',
    type: 2
  }
]);
const flag = ref(1);
const modal = ref(1);
const imgUrl = ref();

const cropper = ref<TVueCropper>();

const visible = ref(false);
const validateStatus = ref<
  'validating' | 'error' | 'success' | 'warning' | undefined
>('validating');
const help = ref('');
const toast = (e: 1 | 2) => {
  flag.value = e;
  console.log(123, flag.value, e);

  if (e === 1) {
    imgUrl.value = userData.headPortrait;
  } else {
    imgUrl.value = userData.personalHeadPortrait;
  }
  visible.value = true;
};
const customRequest = (option: RequestOption): any => {
  const { onProgress, onError, onSuccess, fileItem, name } = option;
  let file: any = fileItem.file;
  var reader = new FileReader();
  reader.onload = (e) => {
    if (e.target && e.target.result && typeof e.target.result === 'object') {
      // 把Array Buffer转化为blob 如果是base64不需要
      imgUrl.value = window.URL.createObjectURL(new Blob([e.target.result]));
    } else if (e.target && e.target.result) {
      imgUrl.value = e.target.result;
    } else {
      Message.error('上传出错');
    }
  };
  reader.readAsDataURL(file);
};
const handleOk = async () => {
  let base64 = '';
  cropper.value.getCropData(async (data: string) => {
    base64 = data;
    const url = await avatarSetting(base64);
    if (flag.value === 1) {
      userData.headPortrait = url;
    } else {
      userData.personalHeadPortrait = url;
    }
    console.log(
      123,
      flag.value,
      userData.headPortrait,
      userData.personalHeadPortrait,
      url
    );
  });

  visible.value = false;
};
const handleOkMobile = () => {
  if (phoneNumberPattern.test(newMobile.value)) {
    userData.mobile = newMobile.value;
    infoData[0].data = newMobile.value;
    Message.info('修改成功');
    validateStatus.value = 'validating';
    help.value = '';
    setTimeout(() => {
      visibleMobile.value = false;
      newMobile.value = '';
    }, 500);
  } else {
    validateStatus.value = 'error';
    help.value = '手机号码格式错误';
  }
};
const handleOkPassword = () => {
  if (Password.value === newPassword.value) {
    userData.password = Password.value;
    Message.info('修改成功');
    validateStatus.value = 'validating';
    help.value = '';
    setTimeout(() => {
      visiblePassword.value = false;
      Password.value = '';
      newPassword.value = '';
    }, 500);
  } else {
    validateStatus.value = 'error';
    help.value = '密码不匹配';
  }
};
const open = (key: string, type: number) => {
  modal.value = type;
  switch (key) {
    case 'mobile':
      visibleMobile.value = true;
      break;
    case 'password':
      visiblePassword.value = true;
      // visibleMobile.value = true;
      break;

    default:
      break;
  }
};
const save = async () => {
  const { headPortrait, personalHeadPortrait, mobile, password, ctlValue } =
    cloneDeep(userData);
  if (ctlValue && Array.isArray(ctlValue) && ctlValue.length !== 0) {
    password
      ? await putPersonalInfo({
          headPortrait,
          personalHeadPortrait,
          mobile,
          password,
          ctlValue
        })
      : await putPersonalInfo({
          headPortrait,
          personalHeadPortrait,
          mobile,
          ctlValue
        });
  } else {
    password
      ? await putPersonalInfo({
          headPortrait,
          personalHeadPortrait,
          mobile,
          password
        })
      : await putPersonalInfo({
          headPortrait,
          personalHeadPortrait,
          mobile
        });
  }
  userStore.personalHeadPortrait = personalHeadPortrait;
  userStore.headPortrait = headPortrait;
  localStorage.setItem('personalHeadPortrait', personalHeadPortrait);
  localStorage.setItem('headPortrait', headPortrait);
  router.back();
};
onMounted(async () => {
  const {
    name,
    headPortrait,
    personalHeadPortrait,
    mobile,
    jobNumber,
    ctlValue
  } = await personalInfo();
  Object.assign(userData, {
    name,
    headPortrait,
    personalHeadPortrait,
    mobile,
    jobNumber,
    ctlValue
  });

  if (mobile) {
    infoData[0].data = mobile;
    infoData[0].type = 1;
  }
  infoData[1].data = '******';
  infoData[1].type = 1;
});
</script>

<style lang="less" scoped>
main {
  margin-bottom: 60px;
  overflow: hidden;
  padding: 10px 20px;

  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f2f2f2;
    margin-bottom: 10px;
    padding: 0 10px;
    background-color: #e8f0ff;
    border-radius: 5px;

    h2 {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      // padding: 10px;

      &::before {
        content: '';
        display: inline-block;
        width: 7px;
        height: 30px;
        background-color: #165dff;
        margin-right: 10px;
      }
    }
  }
  .personnel {
    width: 100%;
    height: 300px;
    border: 1px solid #e4e4e4;
    border-radius: 5px;
    display: flex;
    flex-wrap: wrap;
    padding: 20px;
    box-sizing: border-box;

    .item {
      display: flex !important;
      font-size: 18px;
    }
  }
}
.cut {
  margin: 10px auto;
  width: 500px;
  height: 300px;
}
footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}
.grid-demo {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
}
.title-box {
  position: relative;
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 36px;
    border-radius: 4px;
    font-weight: 700;
    margin-bottom: 10px;
    background: #edeffd;
  }
}
.title-box::before {
  position: absolute;
  // top: 33px;
  left: 10px;
  display: inline-block;
  height: 18px;
  top: 50%;
  transform: translateY(-50%);
  width: 10px;
  margin-right: 20px;
  border-radius: 2px;
  content: '';
  background-color: #165dff;
}
.infoDataAAA {
  :deep(div:first-child(1)) {
    margin-right: 80px;
  }
}
</style>
